//
//  CTCOfflineConsultQuestionDetailVC.m
//  CTC
//
//  Created by zhangfuwei on 2017/4/17.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "CTCOfflineConsultQuestionDetailVC.h"
#import "CTCOfflineConsultRecordsModel.h"


#import <Masonry.h>


@interface CTCOfflineConsultQuestionDetailVC ()
/** 咨询问题uuid */
@property (nonatomic, copy) NSString *uuid;

/** 咨询问题详情 */
@property (nonatomic, strong) CTCOfflineConsultRecordsDataModel *detailModel;

/** scrollView */
@property (nonatomic, strong) UIScrollView *scrollView;
/** 头像 */
@property (nonatomic, strong)   UIImageView *headImageView;
/** 名称 */
@property (nonatomic, strong)   UILabel *nameLabel;
/** 公司 */
@property (nonatomic, strong)   UILabel *companyNameLabel;
/** 电话 */
@property (nonatomic, strong)   UIButton *phoneBtn;
/** 位置 */
@property (nonatomic, strong)   UIButton *locationBtn;
/** 内容 */
@property (nonatomic, strong)   UILabel *contentLabel;
/**  服务起止时间 */
@property (nonatomic, strong)   UIButton *severBtn;
/**服务创建时间 */
@property (nonatomic, strong)   UIButton *createBtn;
/**  接单 */
@property (nonatomic, strong)   UIButton *orderAcceptBtn;
/**  拒单 */
@property (nonatomic, strong)   UIButton *orderRefuseBtn;

/** 分割线 */
//@property (nonatomic, strong)   UIView  *splitLine;


@end

@implementation CTCOfflineConsultQuestionDetailVC

-(instancetype)initWithQuestionDetailModel:(CTCOfflineConsultRecordsDataModel *)detailModel {
    self = [super init];
    if (self) {
        _detailModel = detailModel;
    }
    return self;
}

- (instancetype)initWithQuestionUuid:(NSString *)uuid {
    self = [super init];
    if (self) {
        _uuid = uuid;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupConfig];
    
    if (_detailModel) {
        [self loadUI];
        
    }else if (_uuid) {
        [self requestQuestionDetailWithUUID:_uuid];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- 视图初始化

- (void)setupConfig {
    self.title = @"线下咨询";
    self.view.backgroundColor = HEXCOLOR(0xf9f9f9);
    
}

- (void)loadUI {
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-64)];
    _scrollView.backgroundColor = [UIColor whiteColor];
//    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_scrollView];
    
    //  视图间距
    CGFloat kMargin     = 10;
    CGFloat kViewMargin = 15;
    CGFloat kEdgeMargin = 20;
    CGFloat imgW = 50;
    
    _headImageView = [[UIImageView alloc] initWithFrame:CGRectMake(kViewMargin, kMargin, imgW, imgW)];
    _headImageView.layer.cornerRadius = 5;
    _headImageView.clipsToBounds = YES;
    
    _nameLabel          = [[UILabel alloc] init];
    _contentLabel       = [[UILabel alloc] init];
    _companyNameLabel   = [[UILabel alloc] init];
    
    _contentLabel.numberOfLines     = 0;
    
    _nameLabel.font         = CHINESE_SYSTEM(15);
    _companyNameLabel.font      = CHINESE_SYSTEM(12);
    _contentLabel.font      = CHINESE_SYSTEM(14);
    
    _nameLabel.textColor    = HEXCOLOR(0x4c5c6c);
    _companyNameLabel.textColor    = HEXCOLOR(0x666666);


    _contentLabel.textColor = HEXCOLOR(0x333333);

    // 位置,电话 按钮
    _severBtn           = [UIButton buttonWithType:UIButtonTypeCustom];
    _createBtn          = [UIButton buttonWithType:UIButtonTypeCustom];
    _phoneBtn          = [UIButton buttonWithType:UIButtonTypeCustom];
    _locationBtn          = [UIButton buttonWithType:UIButtonTypeCustom];
    
    _createBtn.titleLabel.font      = CHINESE_SYSTEM(12);
    _locationBtn.titleLabel.font      = CHINESE_SYSTEM(12);
    _phoneBtn.titleLabel.font      = CHINESE_SYSTEM(12);

    [_createBtn setTitleColor:HEXCOLOR(0xb7b7b7) forState:UIControlStateNormal];
    [_locationBtn setTitleColor:HEXCOLOR(0x666666) forState:UIControlStateNormal];
    
    [_locationBtn setImage:[UIImage imageNamed:@"offline_location"] forState:UIControlStateNormal];
    _locationBtn.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    
    // 灰色外边框+内边距
    [_createBtn.layer setBorderColor:HEXCOLOR(0xf0f0f0).CGColor];
    [_createBtn.layer setBorderWidth:1];
    [_severBtn.layer setBorderColor:HEXCOLOR(0xf0f0f0).CGColor];
    [_severBtn.layer setBorderWidth:1];
    
    _createBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _severBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _createBtn.titleEdgeInsets = UIEdgeInsetsMake(17, kMargin, 17, 0);
    _severBtn.titleEdgeInsets = UIEdgeInsetsMake(17, kMargin, 17, 0);
    
    _phoneBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _phoneBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 7, 0, 0);
    _locationBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _locationBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 7, 0, 0);

    
    //  接单/拒单按钮
    _orderAcceptBtn         = [[UIButton alloc] init];
    [_orderAcceptBtn setTitle:@"接单" forState:UIControlStateNormal];
    [_orderAcceptBtn addTarget:self action:@selector(orderAcceptBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    _orderAcceptBtn.backgroundColor = HEXCOLOR(0xfb6b2f);
    _orderAcceptBtn.layer.cornerRadius = 25;
    _orderAcceptBtn.clipsToBounds = YES;
    _orderAcceptBtn.titleLabel.font      = CHINESE_SYSTEM(16);
    _orderAcceptBtn.tag = 1;
    
    _orderRefuseBtn         = [[UIButton alloc] init];
    [_orderRefuseBtn setTitle:@"不接单" forState:UIControlStateNormal];
    [_orderRefuseBtn addTarget:self action:@selector(orderAcceptBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    _orderRefuseBtn.backgroundColor = COLOR_NAVBAR_BLUE;
    _orderRefuseBtn.layer.cornerRadius = 25;
    _orderRefuseBtn.clipsToBounds = YES;
    _orderRefuseBtn.titleLabel.font = CHINESE_SYSTEM(16);
    _orderRefuseBtn.tag = 2;
    
    // 添加子控件
    [_scrollView addSubview:_headImageView];
    
    [_scrollView addSubview:_nameLabel];
    [_scrollView addSubview:_companyNameLabel];
    [_scrollView addSubview:_contentLabel];
    
    [_scrollView addSubview:_severBtn];
    [_scrollView addSubview:_createBtn];
    [_scrollView addSubview:_locationBtn];
    [_scrollView addSubview:_phoneBtn];

    [_scrollView addSubview:_orderAcceptBtn];
    [_scrollView addSubview:_orderRefuseBtn];

    // 约束布局

    [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_headImageView.mas_right).offset(12);
        make.top.equalTo(_scrollView).offset(kEdgeMargin);
        make.height.equalTo(@(15));
    }];
    
    
    [_companyNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_nameLabel);
        make.top.equalTo(_scrollView).offset(43);
        make.height.equalTo(@(12));
    }];
    
    
    [_phoneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_nameLabel);
        make.top.equalTo(_scrollView).offset(63);
        make.right.equalTo(self.view).offset(-1*kViewMargin);
        make.height.width.equalTo(@(10));
    }];

    
    [_locationBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_nameLabel);
        make.right.equalTo(self.view).offset(-1*kViewMargin);
        make.top.equalTo(_scrollView).offset(85);
        make.height.equalTo(@(10));
    }];

    
    [_contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_locationBtn.mas_bottom).offset(8);
        make.left.equalTo(_scrollView).offset(17);
        make.right.equalTo(self.view).offset(-1*17);
    }];
    
    [_createBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_contentLabel.mas_bottom).offset(kMargin);
        make.left.right.equalTo(_contentLabel);
        make.height.equalTo(@43);
    }];

    [_severBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_createBtn.mas_bottom).offset(kViewMargin);
        make.left.equalTo(_scrollView).offset(kViewMargin);
        make.right.equalTo(self.view).offset(-1*kViewMargin);
        make.height.equalTo(@45);
    }];
    
    [_orderAcceptBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_severBtn.mas_bottom).offset(25);
        make.left.equalTo(_scrollView).offset(kViewMargin);
        make.right.equalTo(self.view).offset(-1*kViewMargin);
        make.height.equalTo(@50);
    }];
    
    [_orderRefuseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_severBtn.mas_bottom).offset(90);
        make.left.right.equalTo(_orderAcceptBtn);
        make.height.equalTo(@50);
        make.bottom.equalTo(_scrollView).offset(-1*kEdgeMargin);
    }];

    // 数据赋值
    [SDWebImageTool imageView:_headImageView imageName:_detailModel.headImg placeHolder:@"default-head" showProgress:NO];
    
    
    _nameLabel.text = _detailModel.bname;
    _companyNameLabel.text = _detailModel.companyName;
    _contentLabel.text = _detailModel.content;
    
    [_phoneBtn setTitle:_detailModel.status.intValue == 1?_detailModel.phone:@"联系方式接单后显示" forState:UIControlStateNormal];
    [_phoneBtn setImage:[UIImage imageNamed:_detailModel.status.intValue == 1?@"offline_phone":nil] forState:UIControlStateNormal];
    [_phoneBtn setTitleColor:_detailModel.status.intValue == 1?COLOR_NAVBAR_BLUE:HEXCOLOR(0x00c44e) forState:UIControlStateNormal];
    
    [_locationBtn setTitle:_detailModel.location?:@"无法定位" forState:UIControlStateNormal];
    _orderRefuseBtn.hidden = _detailModel.status.intValue != 0?YES:NO;
    _orderAcceptBtn.hidden = _detailModel.status.intValue != 0?YES:NO;
    
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"服务时间: %@ - %@",[NSDate stringFromTimestamp:_detailModel.createTime dateFormat:@"yyyy MM dd"],[NSDate stringFromTimestamp:_detailModel.endTime dateFormat:@"yyyy MM dd"]] attributes:@{NSForegroundColorAttributeName:COLOR_NAVBAR_BLUE,NSFontAttributeName:CHINESE_SYSTEM(13)}];
    [attStr setAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]} range:NSMakeRange(0, 4)];
    
    [_severBtn setAttributedTitle:attStr forState:UIControlStateNormal];
    [_createBtn setTitle:[NSString stringWithFormat:@"%@",[NSDate stringFromTimestamp:_detailModel.createTime]] forState:UIControlStateNormal];
    
    
}



#pragma mark -- 网络请求

- (void)requestQuestionDetailWithUUID:(NSString *)uuid {
    [MBProgressHUD showActivityMessageInView:@"数据加载中..."];
    if (uuid == nil) {
        [MBProgressHUD showErrorMessage:@"请求参数有误"];
        return;
    }
    
    [RequestTool POST:kOfflineConsultQuestionDetailURL
           parameters:@{@"uuid":uuid}
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  DeLog(@"问题详情--%@",responseObject);
                  NSString *code = responseObject[@"code"];
                  NSString *des = responseObject[@"des"];
                  NSDictionary *data = responseObject[@"data"];
                  
                  if (code.intValue == 1) {
                      [MBProgressHUD showSuccessMessage:des];
                      if ([data isKindOfClass:[NSDictionary class]]) {
                          
                          _detailModel = [CTCOfflineConsultRecordsDataModel yy_modelWithDictionary:data];
                          [self loadUI];
                      }
                      
                  }else if (code.intValue == 2){
                      [MBProgressHUD showTipMessageInView:@"请登录"];
                      [CTCUserModel shareUser].login = NO;
                      [self presentViewController:[CTCLoginViewController viewControllerFromStoryboard] animated:YES completion:nil];
                      
                  }else {
                      [MBProgressHUD showErrorMessage:des];
                      
                  }
              }
              failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  [MBProgressHUD showErrorMessage:@"网络不给力,请检测网络" timer:2.5];
                  DeLog(@"error ---%@",error);
                  
              }
     ];
}


/** 
 uuid 线下咨询id
 type 1接单 2拒单
 */
- (void)requestServiceDoneSubmitionWithOfflineConsultID:(NSString *)uuid type:(NSString *)type{
    

    
    [RequestTool POST:kOfflineConsultOrderURL
           parameters:@{@"uuid":uuid?:@"",@"type":type?:@"1"}
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  DeLog(@"接单,拒单--%@",responseObject);
                  
                  NSString *des = responseObject[@"des"];
                  NSString *code = responseObject[@"code"];
            
                  if (code.intValue == 1) {
                      [MBProgressHUD showSuccessMessage:type.intValue == 1?@"接单成功":@"拒单成功"];
                      
                      _orderRefuseBtn.hidden = YES;
                      _orderAcceptBtn.hidden = YES;
                      [_phoneBtn setTitle:type.intValue == 1?_detailModel.phone:@"联系方式接单后显示" forState:UIControlStateNormal];
                      [_phoneBtn setImage:[UIImage imageNamed:type.intValue == 1?@"offline_phone":nil] forState:UIControlStateNormal];
                      [_phoneBtn setTitleColor:type.intValue == 1?COLOR_NAVBAR_BLUE:HEXCOLOR(0x00c44e) forState:UIControlStateNormal];



                  }else if (code.intValue == 2){
                      [MBProgressHUD showTipMessageInView:@"请登录"];
                      [CTCUserModel shareUser].login = NO;
                      [self presentViewController:[CTCLoginViewController viewControllerFromStoryboard] animated:YES completion:nil];
                      
                  }else{
                      [MBProgressHUD showErrorMessage:des];
                  }
              }
              failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  [MBProgressHUD showErrorMessage:@"网络不给力,请检测网络" timer:2.5];
                  DeLog(@"error ---%@",error);
                  
              }
     ];
    
}
#pragma mark -- private methods
//-(void)setDetailModel:(CTCOfflineConsultRecordsDataModel *)detailModel {
//    _detailModel = detailModel;
//    
//    [SDWebImageTool imageView:_headImageView imageName:detailModel.headImg placeHolder:@"default-head" showProgress:NO];
//    
//    _nameLabel.text = detailModel.bname;
//    _contentLabel.text = detailModel.content;
//}

- (void)orderAcceptBtnClick:(UIButton *)btn {
    
    !btn.tag?: [self requestServiceDoneSubmitionWithOfflineConsultID:_detailModel.uuid type:[NSString stringWithFormat:@"%ld",btn.tag]];
    
}


@end
